from typing import List, Optional
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession

from core.document import document_category as category_service
from schemas.document.document_category import (
    DocumentCategoryCreate, DocumentCategoryUpdate, DocumentCategoryResponse,
    DocumentCategoryTreeResponse, CategoryMoveRequest
)
from db.session import get_db
from log import log_api, log_error

router = APIRouter(
    prefix="/document-categories",
    tags=["document-categories"]
)


@router.get("/", response_model=List[DocumentCategoryTreeResponse])
async def get_category_tree(db: AsyncSession = Depends(get_db)):
    """
    获取文档分类树结构
    
    返回完整的分类树，包含每个分类的文档数量统计
    """
    log_api("获取文档分类树结构", module="router.document_category")
    try:
        return await category_service.get_category_tree(db)
    except Exception as e:
        log_error(f"获取分类树失败: {str(e)}", exc_info=True, module="router.document_category")
        raise HTTPException(status_code=500, detail="获取分类树失败")


@router.post("/", response_model=DocumentCategoryResponse)
async def create_category(
    category: DocumentCategoryCreate,
    db: AsyncSession = Depends(get_db)
):
    """
    创建新的文档分类
    
    - **name**: 分类名称（必填）
    - **icon**: 分类图标（可选，默认📄）
    - **color**: 分类颜色（可选，默认#666666）
    - **description**: 分类描述（可选）
    - **parent_id**: 父分类ID（可选，为空则创建根分类）
    - **sort_order**: 排序顺序（可选，默认0）
    """
    log_api(f"创建文档分类: {category.name}", module="router.document_category")
    try:
        db_category = await category_service.create_category(db, category)
        return DocumentCategoryResponse.model_validate(db_category)
    except ValueError as e:
        log_error(f"创建分类参数错误: {str(e)}", module="router.document_category")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        log_error(f"创建分类失败: {str(e)}", exc_info=True, module="router.document_category")
        raise HTTPException(status_code=500, detail="创建分类失败")


@router.put("/{category_id}", response_model=DocumentCategoryResponse)
async def update_category(
    category_id: UUID,
    category: DocumentCategoryUpdate,
    db: AsyncSession = Depends(get_db)
):
    """
    更新文档分类信息
    
    - **category_id**: 要更新的分类ID
    - 其他字段均为可选，只更新提供的字段
    """
    log_api(f"更新文档分类: {category_id}", module="router.document_category")
    try:
        updated_category = await category_service.update_category(db, category_id, category)
        if not updated_category:
            raise HTTPException(status_code=404, detail="分类不存在")
        return DocumentCategoryResponse.model_validate(updated_category)
    except ValueError as e:
        log_error(f"更新分类参数错误: {str(e)}", module="router.document_category")
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        log_error(f"更新分类失败: {str(e)}", exc_info=True, module="router.document_category")
        raise HTTPException(status_code=500, detail="更新分类失败")


@router.delete("/{category_id}")
async def delete_category(
    category_id: UUID,
    move_request: Optional[CategoryMoveRequest] = None,
    db: AsyncSession = Depends(get_db)
):
    """
    删除文档分类
    
    - **category_id**: 要删除的分类ID
    - **move_request**: 可选的文档迁移请求，指定文档迁移的目标分类
    
    注意：
    - 不能删除系统预设分类
    - 不能删除包含子分类的分类
    - 删除时可以指定将分类下的文档迁移到其他分类
    """
    log_api(f"删除文档分类: {category_id}", module="router.document_category")
    try:
        move_to_category_id = move_request.target_category_id if move_request else None
        success = await category_service.delete_category(db, category_id, move_to_category_id)
        
        if not success:
            raise HTTPException(status_code=404, detail="分类不存在")
        
        return {"message": "分类删除成功"}
    except ValueError as e:
        log_error(f"删除分类参数错误: {str(e)}", module="router.document_category")
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        log_error(f"删除分类失败: {str(e)}", exc_info=True, module="router.document_category")
        raise HTTPException(status_code=500, detail="删除分类失败")


@router.get("/statistics")
async def get_category_statistics(db: AsyncSession = Depends(get_db)):
    """
    获取分类统计信息
    
    返回：
    - 总分类数
    - 系统分类数
    - 自定义分类数
    - 总文档数
    """
    log_api("获取分类统计信息", module="router.document_category")
    try:
        return await category_service.get_category_statistics(db)
    except Exception as e:
        log_error(f"获取分类统计失败: {str(e)}", exc_info=True, module="router.document_category")
        raise HTTPException(status_code=500, detail="获取统计信息失败")